package com.xh.bussiness.teachbook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.teachbook.dao.TeachingBookNumberMapper;
import com.xh.bussiness.teachbook.model.TeachingBookNumber;
import com.xh.bussiness.teachbook.service.ITeachingBookNumberService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2019/9/17
 */
@Service
public class TeachingBookNumberServiceImpl extends BaseServiceImpl<TeachingBookNumberMapper,TeachingBookNumber> implements ITeachingBookNumberService {

    @Override
    public void deleteByTeachingBookId(String teachingBookId) {
        this.dao.deleteByTeachingBookId(teachingBookId);
    }

    @Override
    public void saveTeachingBookNumber(String teachingBookId, String refId, String type, String contractId) {
        QueryWrapper<TeachingBookNumber> numberQueryWrapper = new QueryWrapper<>();
        numberQueryWrapper.eq("ref_id", refId);
        numberQueryWrapper.eq("contract_id", contractId);
        numberQueryWrapper.orderByDesc("num");

        Integer number = 1;
        List<TeachingBookNumber> teachingBookNumberList = this.dao.selectList(numberQueryWrapper);
        if (!CollectionUtils.isEmpty(teachingBookNumberList)) {
            number = teachingBookNumberList.get(0).getNum() + 1;
        }

        TeachingBookNumber newTeachingBookNumber = new TeachingBookNumber();
        newTeachingBookNumber.setContractId(contractId);
        newTeachingBookNumber.setRefId(refId);
        newTeachingBookNumber.setType(Integer.parseInt(type));
        newTeachingBookNumber.setTeachingBookId(teachingBookId);
        newTeachingBookNumber.setNum(number);
        this.dao.insert(newTeachingBookNumber);
    }

    @Override
    public TeachingBookNumber queryTeachingBookNumberByTeachingBookId(String teachingBookId) {
        QueryWrapper<TeachingBookNumber> numberQueryWrapper = new QueryWrapper<>();
        numberQueryWrapper.eq("teaching_book_id", teachingBookId);
        return super.dao.selectOne(numberQueryWrapper);
    }

    @Override
    public TeachingBookNumber queryPreTeachingBokNumber(String refId, Integer type, String contractId, Integer num) {
        QueryWrapper<TeachingBookNumber> qw = new QueryWrapper<>();
        qw.eq("ref_id", refId);
        qw.eq("type", type);
        if (!StringUtils.isEmpty(contractId)) {
            qw.eq("contract_id", contractId);
        }
        qw.eq("num", num);
        return this.dao.selectOne(qw);
    }

}
